<?php
namespace app\middleware;

use app\data\service\JwtTokenService;

class CheckToken
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $route = $this->get_route($request->url());
        //白名单
        $white_list = ['user/login', 'user/register','others/global_data','others/page','others/banner','user/find_pwd'];//路由白名单
        if (!in_array($route, $white_list)) {
            $token = $request->header('token');
            $jwt = new JwtTokenService();
            $res = $jwt->check_token($token);
            if ($res['code'] == 2001) {
                header("token:{$res['token']}");
            }if ($res['code'] == 401) {
                return json(['code' => $res['code']]);
            }
            $request->uid = $res['data']->id;
        }
        return $next($request);
    }

    //截取URL地址获得路由
    private function get_route($url)
    {
        $regex = "#v1.(.*)#";
        preg_match_all($regex, $url, $res);
        $url =  $res[1][0];
        $pos =strpos($url,'?');
        if( $pos!== false){
            $url = substr($url,0,$pos);
        }
        return $url;
    }
}

